
/**
 * Module dependencies.
 */

var express = require('express'),
  routes = require('./routes'),
  user = require('./routes/user'),
  http = require('http'),
  path = require('path'),
	express_velocity = require('./libs/express_velocity.js'),
	similarity = require('./libs/LevenshteinDistance.js'),
	https = require('https');


var app = express();

app.configure(function(){
	app.set('port', process.env.PORT || 3000);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'vm');
	app.engine('.vm',express_velocity.render);
	app.use(express.favicon());
	app.use(express.logger('dev'));
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(express.cookieParser());
	app.use(express.cookieSession({
		secret:'bluishoul'
	}));
	app.use(app.router);
	app.use(require('stylus').middleware(__dirname + '/public'));
	app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});
var port = 88;
var oauth = {
	client_id:'bluishoul',
	client_secret:'jHjcfAd66a5pc7bHJHcKLMuHoLc9Gthi',
	redirect_uri:'http://192.168.1.88:88/login/after'
}
var code_url = 'https://www.oschina.net/action/oauth2/authorize?client_id='+oauth.client_id+'&redirect_uri='+encodeURI(oauth.redirect_uri)+'&response_type=code';
var token_url = 'https://www.oschina.net/action/oauth2/token?client_id='+oauth.client_id+'&client_secret='+oauth.client_secret+'&grant_type=authorization_code&redirect_uri='+encodeURI(oauth.redirect_uri)+'&code=';
var search_url = 'http://www.oschina.net/action/openapi/search_list?catalog=project&q=';
var project_pattern = /http:\/\/www\.oschina\.net\/p\/(.+)/;

var array_count = function(arr){
	var count = 0;
	for(var i in arr){
		count++;
	}
	return count;
};

var search = function(key,callback){
	var keys = key && key.split(',');
	var list = {};
	keys.forEach(function(key){
		http.get(search_url+encodeURI(key), function(response) {
			var fr = '';
			response.on('data', function(d) {
				fr+= d.toString();
			});
			response.on('end', function () {
				try{
					var result = JSON.parse(fr);
					list[key] = result.searchlist;
					if(array_count(list)==keys.length)
						callback && callback(null,list);
				}catch(e){
				}
			});
		}).on('error', function(e) {
				console.error(e);
			});
	});
}

var route = {
	index:function(req,res){
		var context = {
			body:req.body,
			root:function(){
				return 'http://'+req.host+(port===80?'':':'+port);
			},
			access_token:req.session.access_token
		};
		if(req.query.js){
			var url = app.get('views')+'/index.vm';
			var js_redirect = req.header('Referer');
			req.session.js_redirect = js_redirect;
			express_velocity.render(url,context,function(err,tpl){
				res.set('Content-Type', 'text/javascript');
				res.send('document.write(decodeURI("'+encodeURI(tpl)+'"))');
			});
		}else{
			res.render('index.vm', context);
		}
	},
	login:function(req,res){
		var step = req.params.step;
		if(step === 'before'){
			res.redirect(code_url);
		}else if(step === 'after'){
			var code = req.query.code;
			https.get(token_url+code, function(response) {
				response.on('data', function(d) {
					var result = JSON.parse(d.toString());
					console.log(result.access_token);
					req.session.access_token = result.access_token;
					res.redirect(req.session.js_redirect?req.session.js_redirect:'/');
				});
			}).on('error', function(e) {
					console.error(e);
			});
		}
	},
	'post':function(req,res){
		var content = req.body.content+ ' from:'+req.body.url;
		var share_url = 'http://www.oschina.net/action/openapi/tweet_pub?msg='+encodeURIComponent(content)+'&access_token='+req.session.access_token;
		console.log(share_url);
		if(req.body.send_to_oschina === 'on'){
			http.get(share_url, function(response) {
				response.on('data', function(d) {
					var result = JSON.parse(d.toString());
					res.render('post.vm',{
						body:req.body
					});
				});
			}).on('error', function(e) {
					console.error(e);
				});
		}
		else{
			res.render('post.vm',{
				body:req.body
			});
		}
	},
	clean_token:function(req,res){
		req.session.access_token = null;
		res.send('clean success!');
	},
	tips:function(req,res){
		var key = req.query.key;
		var callback = req.query.callback;
		res.set('Content-Type','application/json');
		search(key && key.toLowerCase(),function(e,result){
			if(e){
				console.error(e);
				res.send(callback+'()');
			}else{
				for(var index in result){
					var value = result[index];
					var r = 0;
					var fr = '';
					value.forEach(function(v){
						var mr = v.url.match(project_pattern)[1];
						var w = similarity.init(index.toLowerCase(),mr).get();
						if(r<w){
							r=w;
							fr = v;
							fr.ident = mr;
						}
					});
					result[index] = fr;
				};
				console.log(result);
				res.send(callback+'('+JSON.stringify(result)+')');
			}
		});
	},
	project:function(req,res){

	}
};

app.get('/',route.index);

app.post('/',route.index);

app.get('/login/:step',route.login);

app.post('/post',route.post);

app.post('/clean_token',route.clean_token);

app.post('/tips',route.tips);
app.get('/tips',route.tips);
app.post('/tip/:project',route.project);
app.get('/tip/:project',route.project);

http.createServer(app).listen(port, function(){
  console.log("Express server listening on port "+port );
});

